/*
 * TwitterWhatAreYouDoingServiceAuthenticator.java
 *
 * Created on September 7, 2008, 6:46 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.netbeans.saas.twitter;

import java.io.IOException;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.util.prefs.Preferences;
import canary.LoginDialog;

/**
 *
 * @author hulles
 */
public class TwitterWhatAreYouDoingServiceAuthenticator extends Authenticator {
    private static String userID;
    private static String password;

    private static TwitterWhatAreYouDoingServiceAuthenticator singleton = new TwitterWhatAreYouDoingServiceAuthenticator();
    
    public static void login() throws IOException {
        login(false);
    }
    public static void login(boolean force) throws IOException {
        Preferences pref;
        LoginDialog loginDialog = null;
        
        if (!isValidUsernamePassword()) {
            pref = Preferences.userNodeForPackage(TwitterWhatAreYouDoingServiceAuthenticator.class);
            userID = pref.get("userID", "");
            password = pref.get("password", "");
            if (!isValidUsernamePassword()) {
                if (loginDialog == null) {
                    loginDialog = new LoginDialog(null);
                }
                loginDialog.setVisible(true);
                userID = pref.get("userID", "");
                password = pref.get("password", "");
                if (!isValidUsernamePassword()) {
                    throw new IOException("Invalid username and/or password");
                }
            }
        }
        
        Authenticator.setDefault(singleton);
    }
        
    private static boolean isValidUsernamePassword() {
        return (userID != null && userID.length() > 0 &&
                password != null && password.length() > 0);
    }

    private TwitterWhatAreYouDoingServiceAuthenticator() {
    }

    @Override
    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userID, password.toCharArray());
    }

}
